# -*- coding: UTF-8 -*-
from aiohttp import web
import asyncio
import requests
import time
import pymongo
from datetime import datetime
import json

class WebServer():
    def __init__(self,server="0.0.0.0",port="1234",logger=None,mongo_client=None,redis_client=None):
        self.server = server
        self.port = port
        self.logger = logger
        self.redis_client = redis_client
        self.db = mongo_client['okex_trade']
         # 持仓张数表
        self.table_position = self.db['position']
        self.table_spots_depth = self.db['spots_depth']
        self.table_swap_depth = self.db['swap_depth']
        self.table_futures_depth = self.db['futures_depth']
    def formatJson(self,code=200,msg='ok',data={}):
        return {"code":code,"msg":msg,"data":data}
    async def handle(self,request):
        params = request.rel_url.query
        return web.json_response(self.formatJson(200,"ok",{"input":params['name']}))
    async def holdList(self,request):
        params = request.rel_url.query
        page = 1
        if 'page' in params:
            page = int(params['page'])
        if page <= 0 :
            page = 1
        pageSize = 10
        if 'pageSize' in params:
            pageSize = int(params['pageSize'])
        offset = ( page - 1 ) * pageSize
        count = self.table_position.find().count()
        results = self.table_position.find().skip(offset).limit(pageSize)
        l = []
        for result in results:
            l.append({
                "instrument_id":result['instrument_id'],
                'time':result['time'],
                'amount':result['amount']
            })
        return web.json_response(self.formatJson(200,"ok",{"list":l,"allCount":count,"page":page,"pageSize":pageSize}))
    
    async def depth(self,request):
        params = request.rel_url.query
        page = 1
        if 'page' in params:
            page = int(params['page'])
        if page <= 0 :
            page = 1
        pageSize = 10
        if 'pageSize' in params:
            pageSize = int(params['pageSize'])
        offset = ( page - 1 ) * pageSize
        count = self.table_spots_depth.find().count()
        results = self.table_spots_depth.find().skip(offset).limit(pageSize)
        l = []
        for result in results:
            l.append({
                "instrument_id":result['instrument_id'],
                'time':result['time'],
                'asks':result['asks'],
                'bids':result['bids']
            })
        results = self.table_futures_depth.find().skip(offset).limit(pageSize)
        fl = []
        for result in results:
            fl.append({
                "instrument_id":result['instrument_id'],
                'time':result['time'],
                'asks':result['asks'],
                'bids':result['bids']
            })
        return web.json_response(self.formatJson(200,"ok",{"depth":l,"fdepth":fl,"allCount":count,"page":page,"pageSize":pageSize}))

    async def charts_strategy(self,request):
        self.logger.info("begin")
        params = request.rel_url.query
        symbol = "BTC"
        if 'symbol' in params:
            symbol = params['symbol']
        fromType = "spot"
        if 'fromType' in params:
            fromType = params['fromType']
        toType = "next_week"
        if 'toType' in params:
            toType = params['toType']
        last_time = int(time.time())
        if 'last_time' in params:
            last_time = int(params['last_time'])
        per_time = 5 # 5min
        if 'per_time' in params:
            per_time = int(params['per_time'])
        if per_time <= 0 :
            per_time = 5
        per_time = per_time * 60
        start_time = last_time - 86400 # 最近4h数据
        timeData = []
        timeIndex = {}
        xhData = []
        jcData = []
        qhData = []
        i = 0
        query = {'time':{'$lt': last_time,'$gt': start_time},'symbol':symbol}
        while start_time <= last_time:
            left = start_time % per_time
            index = start_time - left
            timeIndex["{0}".format(index)] = i
            tl = time.localtime(index)
            format_time = time.strftime("%Y/%m/%d %H:%M:%S", tl) 
            timeData.append(format_time)
            start_time += per_time
            i = i+1
        for i in range(len(timeData)):
            xhData.append(0)
            qhData.append(0)
            jcData.append(0)
        results = self.table_spots_depth.find(query)
        l = {}
        for result in results:
            # 以5分钟数据为准 300s 取平均值
            left = result['time'] % per_time
            index = "{0}".format(result['time'] - left)
            if index in l: #现货取最高买价 bids
                l[index] = ( float(l[index])+float(result['bids'][0][0]) ) / 2
            else :
                l[index] = float(result['bids'][0][0])
            if index not in timeIndex:
                continue
            xhData[timeIndex[index]] = l[index]
        results = self.table_position.find(query) # 持仓
        position = {}
        self.logger.info(query)
        for result in results:
            # 以5分钟数据为准 300s 取平均值
            left = result['time'] % per_time
            index = "{0}".format(result['time'] - left)
            if index in position: #持仓量
                position[index] = ( float(position[index])+float(result['amount']) ) / 2
            else :
                position[index] = float(result['amount'])
        query['contractType'] = toType
        self.logger.info(query)
        results = self.table_futures_depth.find(query)
        fl = {}
        for result in results:
            # 以5分钟数据为准 300s 取平均值
            left = result['time'] % per_time
            index = "{0}".format(result['time'] - left)
            if index in fl: #期货取最低卖价 asks
                fl[index] = ( float(fl[index])+float(result['asks'][0][0]) ) / 2
            else :
                fl[index] = float(result['asks'][0][0])
            if index not in timeIndex:
                continue
            qhData[timeIndex[index]] = fl[index]
            jcData[timeIndex[index]] = qhData[timeIndex[index]] - xhData[timeIndex[index]]

        return web.json_response(self.formatJson(200,"ok",{"timeData":timeData,"xhData":xhData,"qhData":qhData,"position":position,"jcData":jcData}))

    def getName(self,typ):
        if typ == "spot":
            return "现货"
        if typ == "swap":
            return "永续"
        if typ == "this_week":
            return "当周"
        if typ == "next_week":
            return "次周"
        if typ == "quarter":
            return "季度"
        if typ == "bi_quarter":
            return "次季"
                

    async def realtime_strategy(self,request):
        params = request.rel_url.query
        
        GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT+0800 (CST)'
        symbol = "BTC"
        if 'symbol' in params:
            symbol = params['symbol']
        l = []
        ls = self.redis_client.get("topdata:{0}".format(symbol))
        # self.logger.info(ls)
        if ls != None:
            l = json.loads(ls)
        difflist = []
        count = len(l)
        index = 0
        for i in range(count):
            src = l[i]
            for j in range(count):
                if j <= i:
                    continue
                if j >= count :
                    break
                dst = l[j]
                price = float(dst['price']) - float(src['price'])
                percent = ( price / float(src['price']) ) * 100
                index = index + 1
                a = {
                    "dst_color": "bg-warning",
                    "dst_contractStr": self.getName(dst['contractType']),
                    "dst_contractType": dst['contractType'],
                    "dst_price": dst['price'],
                    "id": index,
                    "percent":round(percent, 2),
                    "price":round(price, 2),
                    "src_color":"bg-success",
                    "src_contractStr":self.getName(src['contractType']),
                    "src_contractType":src['contractType'],
                    "src_price":src['price'],
                }
                difflist.append(a)

        data = {
            "difflist":difflist,
            "symbol":symbol.lower(),
            "updatetime":datetime.utcnow().strftime(GMT_FORMAT),
            "topdata":l
        }
        return web.json_response(data)

    def run(self):
        app = web.Application()
        app.add_routes([web.get('/', self.handle),web.get('/depth', self.depth),
        web.get('/realtime-strategy', self.realtime_strategy),
        web.get('/charts-strategy', self.charts_strategy),
        web.get('/hold-list', self.holdList)])
        self.logger.info("start web server {0}:{1}".format(self.server,self.port))
        web.run_app(app,port=self.port,host=self.server)